package pers.yurwisher.rubick.common.validator;


import cn.hutool.core.util.NumberUtil;
import pers.yurwisher.rubick.common.validator.annotation.BigDecimalCheck;
import pers.yurwisher.rubick.common.wrapper.ValidResult;

import java.math.BigDecimal;

/**
 * @author yq
 * @date 2020/08/04 10:59
 * @description 数据校验
 * @since V1.0.0
 */
public class BigDecimalCheckValidator extends AbstractCheckValidator<BigDecimalCheck, BigDecimal> {

    private String fieldName;
    private boolean required;
    private int precision;
    private int scale;
    private boolean gtZero;

    @Override
    public void initialize(BigDecimalCheck constraintAnnotation) {
        this.fieldName = constraintAnnotation.fieldName();
        this.required = constraintAnnotation.required();
        this.precision = constraintAnnotation.precision();
        this.scale = constraintAnnotation.scale();
        this.gtZero = constraintAnnotation.gtZero();
    }

    @Override
    public ValidResult getValidResult(BigDecimal value) {
        ValidResult result = new ValidResult(fieldName);
        if (value == null) {
            return result.of(!required, "必填");
        } else {
            if (value.precision() > precision) {
                return result.no("最大长度为", precision);
            }
            if (value.scale() > scale) {
                return result.no("最大小数位为", scale);
            }
            if (gtZero && !NumberUtil.isGreater(value, BigDecimal.ZERO)) {
                return result.no("必须大于0");
            }
        }
        return result.pass();
    }

}
